//初始化编辑器
var testEditor;
$(function () {
    testEditor = editormd("test-editor", {
        width: "100%",
        height: "82vh",
        path: '/editormd/lib/',
        theme: "white",
        previewTheme: "white",
        editorTheme: "pastel-on-white",
        markdown: "",
        codeFold: true,
        saveHTMLToTextarea: true, // 保存 HTML 到 Textarea
        searchReplace: true,
        //watch : false,                // 关闭实时预览
        htmlDecode: "style,script,iframe|on*", // 开启 HTML 标签解析，为了安全性，默认不开启
        //toolbar  : false,             //关闭工具栏
        //previewCodeHighlight : false, // 关闭预览 HTML 的代码块高亮，默认开启
        emoji: true,
        taskList: true,
        tocm: true, // Using [TOCM]
        tex: true, // 开启科学公式TeX语言支持，默认关闭
        flowChart: true, // 开启流程图支持，默认关闭
        sequenceDiagram: true, // 开启时序/序列图支持，默认关闭,
        dialogLockScreen: false, // 设置弹出层对话框不锁屏，全局通用，默认为true
        dialogShowMask: false, // 设置弹出层对话框显示透明遮罩层，全局通用，默认为true
        dialogDraggable: false, // 设置弹出层对话框不可拖动，全局通用，默认为true
        dialogMaskOpacity: 0.4, // 设置透明遮罩层的透明度，全局通用，默认值为0.1
        dialogMaskBgColor: "#000", // 设置透明遮罩层的背景颜色，全局通用，默认为#fff
        imageUpload: true,
        imageFormats: ["jpg", "jpeg", "gif", "png", "bmp", "webp"],
        imageUploadURL: "/api/oss/upload?dir=blogs",  //"/Center/RichTextUpload"
        onload: function () {
            var cacheContent = window.localStorage.getItem("kss_blog_content");
            if (cacheContent) {
                console.log("222222");
                testEditor.setMarkdown(cacheContent);
            }
        },
        onchange: function () {
            //只要文章内容发生改变，就会触发这个函数
            console.log("33333");
            cacheBlog();
        }
    });
    // 同步缓存，初始化
    setCacheBlog();
});

function setCacheBlog() {
    console.log("11111");
    var title = window.localStorage.getItem("kss_blog_title");
    if (title) {
        $("#article_title").val(title);
        vm.blog.title = title;
    }

    var img = window.localStorage.getItem("kss_blog_img");
    if (img) {
        $("#article-img").val(img);
        vm.blog.img = img;
    }

    var desc = window.localStorage.getItem("kss_blog_desc");
    if (desc) {
        $("#article-desc").val(desc)
        vm.blog.description = desc;
    }

    var cid = window.localStorage.getItem("kss_blog_cid")
    if (cid) {
        $("#category").find("option[value='" + cid + "']").prop("selected", true);
        vm.blog.categoryId = cid;
    }
}

// 输入的时候同步缓存
function cacheBlog() {
    //$("#article_title").val()--->根据对应元素的id获取元素的value
    window.localStorage.setItem("kss_blog_title", $("#article_title").val());
    window.localStorage.setItem("kss_blog_img", $("#article-img").val());
    window.localStorage.setItem("kss_blog_desc", $("#article-desc").val());
    window.localStorage.setItem("kss_blog_cid", $("#category").val());
    window.localStorage.setItem("kss_blog_content", testEditor.getMarkdown());
}

function removeBlog() {
    window.localStorage.removeItem("kss_blog_title");
    window.localStorage.removeItem("kss_blog_img");
    window.localStorage.removeItem("kss_blog_desc");
    window.localStorage.removeItem("kss_blog_cid");
    window.localStorage.removeItem("kss_blog_content");
}


const vm = Vue.createApp({
    // 数据模型
    data() {
        return {
            blog: {
                id: "",//新增的时候是null,修改时候是有具体的id
                title: "",
                categoryId: "",
                categoryTitle: "",
                htmlcontent: "",
                content: "",
                description: ""
            },
            categoryList: [
                {id: 1, name: "Java面试", checked: false},
                {id: 2, name: "Web开发", checked: false},
                {id: 3, name: "设计系统", checked: false},
                {id: 4, name: "框架服务", checked: false},
                {id: 5, name: "微服务", checked: false},
                {id: 6, name: "移动APP", checked: false}
            ]
        }
    },


    // 生命周期
    mounted() {
        var blogId = this.$refs.blogId.value;
        // var blogId = document.getElementById("blogId").value;
        // alert(blogId);
        // 请注意：这里一定要加判断，因为添加和修改是公用了一个页面。如果你不加判断，添加也会来执行，这是没意义的
        //  blogId是不是null，肯定执行修改操作,
        if (blogId) {
            this.blog.id = blogId;
            this.getBlog();
        }
    },

    // 事件定义
    methods: {
        // 根据id查询文章信息
        getBlog(callback) {
            axios.get("/api/blog/get/" + this.blog.id).then(res => {
                // 把后台查询的数据赋值给vue数据模型
                // 这里个时候blog是有id的
                this.blog = res.data;
                setTimeout(() => {
                    var content = res.data.content;
                    var cachecontent = window.localStorage.getItem("kss_blog_content") || "";
                    testEditor.setMarkdown(cachecontent.length > content.length ? cachecontent : res.data.content);
                }, 300)
            })
        },

        //这个方法就是专门获取分类名称
        changeCategory(ev) {
            this.blog.categoryTitle = this.getCategoryTitle(this.blog.categoryId);
            cacheBlog();
            // console.log(this.blog.categoryId);
        },

        getCategoryTitle(categoryId) {
            var title = "";
            for (let i = 0; i < this.categoryList.length; i++) {
                if (this.categoryList[i].id == categoryId) {
                    title = this.categoryList[i].name;
                    break;
                }
            }
            // 目的是方便获取
            return title;
        },

        saveBlog() {
            // 1：获取文本编辑器的内容
            this.blog.htmlcontent = testEditor.getHTML();
            this.blog.content = testEditor.getMarkdown();
            this.blog.img = this.$refs.blogimg.value;
            // 2：获取分类标题名称
            this.blog.categoryTitle = this.getCategoryTitle(this.blog.categoryId);
            // console.log(this.blog);
            // // 如果出现了异常就会阻止执行了。
            axios.post("/api/blog/saveupdate", this.blog).then(res => {
                if (this.blog.id) {
                    alert("修改成功!!!")
                    // window.location.href = window.location.href;
                    window.location.href = "/detail/"+res.data.id;
                } else {
                    alert("添加成功!!!")
                    window.location.href = "/?cid=" + this.blog.categoryId;
                    // window.location.href = "/blog/edit/"+res.data.id;
                }
                //移除缓存
                removeBlog();
            });
        },
        //点击预览，清除缓存
        removeLocal(){
            removeBlog();
        }
    }
}).mount("#app");




